package com.gaodun.luffy;

import com.gaodun.luffy.util.StrUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class SubmitConfigDialog extends DialogWrapper {



    protected SubmitConfigDialog(@Nullable Project project, String title) {
        super(project);
        init();
        // 对话框标题
        setTitle(title);
    }

    private JPanel center = new JPanel();
    private JPanel south = new JPanel();

    {
        // 对话框大小
        setSize(600, 300);
    }


    private final JLabel workBaseUrlLabel = new JLabel(" 脚本工作目录        (例如：D:\\build)");
    private final DefaultValueTextField workBaseUrlText = new DefaultValueTextField("D:\\build");

    private final JFileChooser workBaseUrlChooser = new JFileChooser();
    // 创建一个按钮触发目录选择操作
    private JButton selectCommonBasePathButton = new JButton("选择脚本所在目录 (注：idea打包.bat 所在目录)");

    private final JLabel gitAccountLabel = new JLabel(" 代码操作账号        (例如：fengyamin   注：填自己本地登录的Git账号)");
    private final DefaultValueTextField gitAccountText = new DefaultValueTextField("fengyamin");


    private final JLabel oldPackageLabel = new JLabel(" 旧包版本名字        (例如：3.2.2.RELEASE   注：取luffy-listener的master分支使用的版本号)");
    private final DefaultValueTextField oldPackageText = new DefaultValueTextField("3.2.2.RELEASE");
    private final JLabel newPackageLabel = new JLabel(" 新包版本名字        (例如：3.2.3.RELEASE   注：默认取旧包版本名字的第三个数字加1无需填写)");



    // 创建一个方法来打开目录选择对话框并获取目录路径
    private void chooseCommonBasePath() {
        // 设置只能选择目录
        workBaseUrlChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        // 'this' 指向当前窗口组件
        int result = workBaseUrlChooser.showOpenDialog(null);
        if (result == JFileChooser.APPROVE_OPTION) {
            File selectedDir = workBaseUrlChooser.getSelectedFile();
            String dirPath = selectedDir.getAbsolutePath();
            // 假设 workBaseUrlText 是 JTextField，这里将其内容更新为选择的路径
            workBaseUrlText.setText(dirPath);
        }
    }

    @Override
    protected @Nullable
    JComponent createCenterPanel() {
        // 面板布局
        GridLayout gridLayout = new GridLayout(10, 1);
        center.setLayout(gridLayout);
        center.add(workBaseUrlLabel);
        center.add(workBaseUrlText);
        selectCommonBasePathButton.addActionListener(e -> chooseCommonBasePath());
        center.add(selectCommonBasePathButton);
        center.add(new JLabel(" "));
        center.add(gitAccountLabel);
        center.add(gitAccountText);
        center.add(new JLabel(" "));
        center.add(oldPackageLabel);
        center.add(oldPackageText);
        center.add(newPackageLabel);
        return center;
    }

    @Override
    protected JComponent createSouthPanel() {
        // 定义Button，设置居中
        JButton button = new JButton("打包");
        button.setHorizontalAlignment(SwingConstants.CENTER);
        button.setVerticalAlignment(SwingConstants.CENTER);
        south.add(button);
        button.addActionListener(e -> {
            // 参数校验
            String info = validateInputs();
            if (!StrUtil.isEmpty(info)) {
                JOptionPane.showMessageDialog(null,info,"错误提示",JOptionPane.ERROR_MESSAGE);
                return;
            }

            String workBaseUrl= workBaseUrlText.getText();
            String gitAccount= gitAccountText.getText();
            String oldPackage= oldPackageText.getText();

            String[] parts = oldPackage.split("\\.");
            int penultimatePart = Integer.parseInt(parts[parts.length - 2]) + 1;
            parts[parts.length - 2] = String.valueOf(penultimatePart);
            String newPackage= String.join(".", parts);
            if (StrUtil.isEmpty(newPackage)) {
                JOptionPane.showMessageDialog(null,"新版本名称生成失败，请检查旧版本号格式","错误提示",JOptionPane.ERROR_MESSAGE);
                return;
            }

            String pan= workBaseUrl.substring(0, workBaseUrl.indexOf(':'));
            if (StrUtil.isEmpty(pan)) {
                JOptionPane.showMessageDialog(null,"盘获取不到","错误提示",JOptionPane.ERROR_MESSAGE);
                return;
            }

            ExecutorService executor = Executors.newSingleThreadExecutor();
            Runnable task = () -> {
                try {
                    // .bat文件的路径
                    String batFilePath = workBaseUrl+"\\idea打包.bat";
                    // 创建ProcessBuilder实例，添加命令及参数
                    ProcessBuilder pb = new ProcessBuilder(Arrays.asList("cmd", "/c", "start", batFilePath,workBaseUrl,gitAccount,oldPackage,newPackage,pan));
                    // 可以设置工作目录（可选）
                    pb.directory(new File("D:"));
                    // 启动进程
                    pb.start();
                } catch (IOException exception) {
                    exception.printStackTrace();
                }
            };
            executor.execute(task);
            dispose();
        });
        return south;
    }



    private String validateInputs() {
        // 1. 所有文本框内容都不为空
        if (workBaseUrlText.getText().trim().isEmpty() ||
                gitAccountText.getText().trim().isEmpty() ||
                oldPackageText.getText().trim().isEmpty()) {
            return "所有框都不能为空";
        }
        return null;
    }
}

